package com.health.userbackstage.web.control;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.health.userbackstage.pojo.HotSetmeal;
import com.health.userbackstage.pojo.result.Result;
import com.health.userbackstage.service.BusinessService;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/report")
public class BusinessController {

    @Autowired
    private BusinessService businessService;

    @GetMapping
    public Result getBusinessData() throws InterruptedException {
        Map<String, Object> data = businessService.getData();
        return Result.success(data);
    }

    /**
     * 导出excel报表
     */
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletRequest req, HttpServletResponse resp) throws InterruptedException, IOException {
        Map<String, Object> data = businessService.getData();
        //将得到的数据写到excel文件中
        String dirPath = "D:\\upload/";

        String fileName = UUID.randomUUID().toString().replaceAll("-","") + ".xlsx";
        //写出excel目标文件
        File destFile = new File(dirPath,fileName);

        //获取excel写出构建器
        ExcelWriterBuilder excelWriterBuilder = EasyExcel.write(destFile).withTemplate("D:\\upload/report_template.xlsx");
        //根据构建器获取sheet
        WriteSheet sheet = excelWriterBuilder.sheet().build();
        //根据构建器获取对象
        ExcelWriter excelWriter = excelWriterBuilder.build();

        //利用excel写处对象，填充到指定sheet中
        excelWriter.fill(data,sheet);
        List<HotSetmeal> hotSetmeals = (List<HotSetmeal>) data.get("hotSetmeal");
        excelWriter.fill(hotSetmeals,sheet);
        //关闭资源
        excelWriter.finish();

        //将写出的excel文件下载到浏览器端
        //指定要输出的文件类型
        String mimeType = req.getServletContext().getMimeType(fileName);
        resp.setHeader("content-type",mimeType);
        //以附件形式下载
        resp.setHeader("content-disposition","attachment;filename=" + fileName);

        //以字节流的形式写出到浏览器端
        FileInputStream fis = new FileInputStream(destFile);
        ServletOutputStream os = resp.getOutputStream();

        int len = -1;
        byte[] bytes = new byte[1024];
        while ((len=fis.read(bytes)) != -1){
            os.write(bytes,0,len);
        }

        //释放资源
        fis.close();
    }

    @GetMapping("/exportBusinessReport4PDF")
    public void exportBusinessReportPDF(HttpServletRequest req, HttpServletResponse resp) throws InterruptedException, IOException, JRException {
        Map<String, Object> data = businessService.getData();

        List<HotSetmeal> hotSetmeals = (List<HotSetmeal>) data.get("hotSetmeal");

        List list = new ArrayList();

        for (HotSetmeal hotSetmeal : hotSetmeals) {
            Map map = new HashMap();
            map.put("name",hotSetmeal.getName().toString());
            map.put("setmeal_count",hotSetmeal.getSetmeal_count().toString());
            map.put("proportion",hotSetmeal.getProportion().toString());
            list.add(map);
        }

        //利用编译对象，对jrxml文件进行编译，得到jasper文件
        String template = "D:\\upload/health_business3.jrxml";
        String jasperDestPath = "D:\\upload/health_business3.jasper";
        JasperCompileManager.compileReportToFile(template,jasperDestPath);

        //将数据填充到jasper文件中
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperDestPath, data, new JRBeanCollectionDataSource(list));

        //将填充后的jasper按照要求导出对应格式
        String fileName = UUID.randomUUID().toString().replaceAll("-","") + ".pdf";

        String pdfPath = "D:\\upload/" + fileName;
        JasperExportManager.exportReportToPdfFile(jasperPrint,pdfPath);

        File destFile = new File(pdfPath,fileName);

        //将文件下载到浏览器
        //指定要输出的文件类型
        String mimeType = req.getServletContext().getMimeType(fileName);
        resp.setHeader("content-type",mimeType);
        //以附件形式下载
        resp.setHeader("content-disposition","attachment;filename=" + fileName);

        //以字节流的形式写出到浏览器端
        FileInputStream fis = new FileInputStream(pdfPath);
        ServletOutputStream os = resp.getOutputStream();

        int len = -1;
        byte[] bytes = new byte[1024];
        while ((len=fis.read(bytes)) != -1){
            os.write(bytes,0,len);
        }

        //释放资源
        fis.close();
    }


}
